package com.duo.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.duo.dto.FileDto;
import com.duo.enums.minio.MinIOConfig;
import com.duo.result.BaseResult;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.rowset.serial.SerialException;

/**
 * @Author: Xrx
 * @Description:
 * @CreateTime: 2023/7/6 20:54
 */

@RestController("/file")
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MinIOConfig minIOConfig;


    /**
     * 上传文件
     * @param file 文件
     * @return
     */
    @PostMapping("/upload")
    public Object uploadFile(@RequestBody MultipartFile file) throws SerialException {
        MinioClient minioClient = minIOConfig.getMinioClient();
        if (minioClient == null) {
            throw new SerialException("连接MinIO服务器失败");
        }
        return minIOConfig.uploadFile(minioClient, file);
    }

    /**
     * 删除文件
     * @return
     */
    @DeleteMapping("/delete")
    public Object deleteFile(@RequestBody FileDto fileDeleteDto) throws SerialException {
        MinioClient minioClient = minIOConfig.getMinioClient();
        if (ObjectUtil.isNull(minioClient)) {
            throw new SerialException("连接MinIO服务器失败");
        }
        boolean flag = minIOConfig.deleteFile(minioClient, fileDeleteDto.getFileName());
        return flag ? BaseResult.success("删除成功") : BaseResult.success("删除失败");
    }

    /**
     * 文件预览
     */
    @PostMapping("/preview")
    public Object previewFile(@RequestBody FileDto fileDto) throws SerialException {
        MinioClient minioClient = minIOConfig.getMinioClient();
        if (minioClient == null) {
            throw new SerialException("连接MinIO服务器失败");
        }
        Integer previewExpiry = 1;
        String previewUrl = minIOConfig.getPreviewUrl(minioClient, fileDto.getFileName(), previewExpiry);
        return BaseResult.success(previewUrl);
    }



}

